<template>
  <div class="prompt-template-container">
    <n-card class="prompt-template-card">
      <template #header>
        <div class="header-content">
          <div class="category-tags">
            <n-tag
              v-for="category in categories"
              :key="category"
              :bordered="selectedCategory === category"
              size="small"
              class="category-tag"
              :style="{ 
                backgroundColor: getCategoryColor(category), 
                color: '#333',
                borderColor: selectedCategory === category ? '#18a058' : 'transparent'
              }"
              @click="selectCategory(category)"
            >
              {{ category }}
            </n-tag>
          </div>
          <div class="header-actions">
            <n-input-group>
              <n-input
                v-model:value="searchKeyword"
                placeholder="搜索..."
                style="width: 180px;"
                @input="handleSearch"
                clearable
                size="small"
              >
                <template #prefix>
                  <n-icon size="14"><SearchOutline /></n-icon>
                </template>
              </n-input>
            </n-input-group>
            <n-button circle size="small" type="primary" @click="createNewTemplate">
              <template #icon>
                <n-icon><AddOutline /></n-icon>
              </template>
            </n-button>
          </div>
        </div>
      </template>

      <!-- 宫格视图 -->
      <div class="scroll-container">
        <n-scrollbar class="grid-scrollbar">
          <div class="grid-container">
            <div
              v-for="template in filteredTemplates"
              :key="template.id"
              class="template-card"
              :style="{ backgroundColor: getCategoryColor(template.category) }"
            >
              <div class="card-header">
                <div class="card-title">{{ template.name }}</div>
                <div class="card-actions">
                  <n-button
                    size="small"
                    quaternary
                    @click="editTemplate(template)"
                  >
                    <template #icon>
                      <n-icon><CreateOutline /></n-icon>
                    </template>
                  </n-button>
                  <n-button
                    size="small"
                    quaternary
                    type="error"
                    @click="deleteTemplate(template)"
                  >
                    <template #icon>
                      <n-icon><TrashOutline /></n-icon>
                    </template>
                  </n-button>
                </div>
              </div>
              <div class="card-content">
                <div class="template-description">{{ template.description }}</div>
              </div>
              <div class="card-footer">
                <n-tag size="small" :style="{ backgroundColor: getCategoryColor(template.category), color: '#333' }">{{ template.category }}</n-tag>
                <span class="usage-count">使用 {{ template.usageCount }} 次</span>
              </div>
            </div>
          </div>
        </n-scrollbar>
      </div>
    </n-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import {
  NButton,
  NInput,
  NInputGroup,
  NTag,
  NIcon,
  NScrollbar,
  useMessage
} from 'naive-ui'
import {
  SearchOutline,
  CreateOutline,
  TrashOutline,
  AddOutline,
} from '@vicons/ionicons5'
import { promptService } from "../services/prompt-service";
import { useRouter } from 'vue-router'

const message = useMessage()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const templates = ref<any[]>([])
const searchKeyword = ref('')
const selectedCategory = ref('全部')

// 分类选项
const categories = computed(() => {
  const cats = ['全部', '通用', '灵感', '大纲', '章节规划', '支线', '细纲', '人设', '正文', '封面', '审稿', '改稿']
  return cats
})

// 为每个分类定义对应的背景色
const getCategoryColor = (category: string) => {
  const colorMap: Record<string, string> = {
 '通用': '#f8fafc', // 浅灰色 - 通用功能
    '灵感': '#fefce8', // 浅黄色 - 灵感创意
    '大纲': '#fee2e2', // 浅红色 - 重要框架
    '章节规划': '#e0e7ff', // 浅靛蓝色 - 结构规划
    '支线': '#fef3c7', // 浅橙色 - 支线内容
    '细纲': '#dcfce7', // 浅绿色 - 细节规划
    '人设': '#f3e8ff', // 浅紫色 - 神秘人物
    '正文': '#cffafe', // 浅青色 - 主要内容
    '封面': '#f0f9ff', // 浅天蓝色 - 外观展示
    '审稿': '#fef2f2', // 浅红色 - 审核环节
    '改稿': '#dcfce7'  // 浅绿色 - 成品接近
  }
  return colorMap[category] || '#fafafa' // 默认颜色
}

// 过滤后的模板
const filteredTemplates = computed(() => {
  let filtered = templates.value

  // 按分类过滤
  if (selectedCategory.value !== '全部') {
    filtered = filtered.filter(t => t.category === selectedCategory.value)
  }

  // 按关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(t =>
      t.name.toLowerCase().includes(keyword) ||
      t.content.toLowerCase().includes(keyword) ||
      t.description?.toLowerCase().includes(keyword)
    )
  }

  return filtered
})

// 方法
const loadTemplates = async () => {
  loading.value = true
  try {
    const response = await promptService.getPromptTemplates()
    if (response.code === 0 && response.data) {
      templates.value = response.data
    } else {
      message.error('加载模板失败: ' + response.msg)
    }
  } catch (error) {
    message.error('加载模板失败: ' + error)
  } finally {
    loading.value = false
  }
}

const refreshData = () => {
  loadTemplates()
  message.success('数据已刷新')
}

const handleSearch = () => {
  // 搜索逻辑已在computed中处理
}

const selectCategory = (category: string) => {
  selectedCategory.value = category
}

const createNewTemplate = () => {
  // 获取TabManager实例
  const tabManager = (window as any).tabManagerInstance;
  
  if (tabManager && tabManager.openTab) {
    // 使用TabManager打开新建页面
    const tabId = `prompt-edit-new`;
    tabManager.openTab({
      id: tabId,
      title: '新增提示词',
      route: '/prompt/edit/new',
      closable: true
    });
  } else {
    // 如果TabManager不可用，回退到直接路由跳转
    console.warn('TabManager不可用，使用直接路由跳转');
    router.push('/prompt/edit/new');
  }
}

const editTemplate = (template: any) => {
  // 获取TabManager实例
  const tabManager = (window as any).tabManagerInstance;
  
  if (tabManager && tabManager.openTab) {
    // 使用TabManager打开编辑页面
    const tabId = `prompt-edit-${template.id}`;
    tabManager.openTab({
      id: tabId,
      title: `编辑提示词: ${template.name}`,
      route: `/prompt/edit/${template.id}`,
      closable: true
    });
  } else {
    // 如果TabManager不可用，回退到直接路由跳转
    console.warn('TabManager不可用，使用直接路由跳转');
    router.push(`/prompt/edit/${template.id}`);
  }
}

const deleteTemplate = async (template: any) => {
  try {
    const response = await promptService.deletePromptTemplate(template.id)
    if (response.code === 0) {
      message.success('删除成功')
      loadTemplates()
    } else {
      message.error('删除失败: ' + response.msg)
    }
  } catch (error) {
    message.error('删除失败: ' + error)
  }
}

// 生命周期
onMounted(() => {
  loadTemplates()
})
</script>

<style scoped>
/* 容器样式 */
.prompt-template-container {
  height: calc(100vh - 80px);
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.prompt-template-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.prompt-template-card :deep(.n-card__content) {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 0;
  overflow: hidden;
}

/* 头部样式 */
.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.category-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.category-tag {
  cursor: pointer;
  transition: all 0.2s ease;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  padding: 4px 10px;
  border: 1px solid transparent;
}

.category-tag:hover {
  opacity: 0.8;
}

/* 滚动容器样式 */
.scroll-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.grid-scrollbar {
  flex: 1;
  height: 100%;
}

.grid-scrollbar :deep(.n-scrollbar-container) {
  height: 100%;
}

.grid-scrollbar :deep(.n-scrollbar-content) {
  height: 100%;
}

/* 网格容器样式 */
.grid-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
  padding: 16px;
  align-content: start;
  min-height: 100%;
}

/* 卡片样式 */
.template-card {
  border: 1px solid #e1e4e8;
  border-radius: 6px;
  padding: 16px;
  transition: all 0.2s ease;
  display: flex;
  flex-direction: column;
  height: 140px;
  width: 100%;
  box-sizing: border-box;
  align-self: start;
  position: relative;
  margin-top: 0;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  cursor: pointer;
  overflow: hidden;
}

.template-card:hover {
  border-color: #18a058;
  box-shadow: 0 2px 8px rgba(24, 160, 88, 0.15);
  transform: translateY(-1px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 4px;
  flex-shrink: 0;
}

.card-title {
  font-weight: 600;
  font-size: 14px;
  color: #24292e;
  flex: 1;
  margin-right: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.card-actions {
  display: flex;
  gap: 4px;
  flex-shrink: 0;
}

.card-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
  overflow: hidden;
}

.template-description {
  color: #586069;
  font-size: 12px;
  line-height: 1.4;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  text-overflow: ellipsis;
  flex: 1;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: auto;
  padding-top: 8px;
  flex-shrink: 0;
}

.usage-count {
  font-size: 12px;
  color: #999;
}

/* 按钮样式 */
.action-btn {
  padding: 4px 8px;
  height: auto;
  font-size: 12px;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.action-btn:hover {
  transform: translateY(-1px);
}

</style>
